package com.buddy.learn.network.netty.demo03.server;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;

/**
 * @author WongZP
 * @date 2022/4/19
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        //1.创建bossGroup线程组: 处理网络事件--连接事件 线程数默认为: 2 * 处理器线程数
        EventLoopGroup boosGroup = new NioEventLoopGroup(1);
        //2.创建workerGroup线程组: 处理网络事件--读写事件 2 * 处理器线程
        EventLoopGroup workGroup = new NioEventLoopGroup();
        //3.创建服务端启动助手
        ServerBootstrap bootstrap = new ServerBootstrap();
        //4.设置线程组
        bootstrap.group(boosGroup,workGroup)
                //5.设置服务端通道实现
                .channel(NioServerSocketChannel.class)
                //6.设置线程队列中等待连接个数
                .option(ChannelOption.SO_BACKLOG,128)
                // 设置活跃状态，child是设置 workGroup
                .childOption(ChannelOption.SO_KEEPALIVE,Boolean.TRUE)
                // 创建一个通道初始化对象
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 向 pipeline 中添加自己的处理器
                        socketChannel.pipeline().addLast(new LineBasedFrameDecoder(2048));
                        socketChannel.pipeline().addLast(new MyNettyServerInboundHandler());
                    }
                });
        // 启动服务端并绑定端口
        ChannelFuture future = bootstrap.bind(8088);
        //给Future添加监听器,监听操作结果
        future.addListener((ChannelFutureListener) channelFuture -> {
            if (channelFuture.isSuccess()){
                System.out.println("bind port success...");
            }else{
                System.out.println("bind port fail!");
            }
        });
        System.out.println("server start...");
        future.channel().closeFuture().sync();
        // 关闭通道(并不是真正意义上的关闭,而是监听通道关闭状态)和关闭连接池
        boosGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}
